<template>
  <div class="task-execution-container">
    <h1 class="page-title">任务执行</h1>
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>
    <div v-else-if="error" class="error-container">
      <el-alert
        :title="error"
        type="error"
        show-icon
      />
    </div>
    <div v-else class="execution-content">
      <el-card class="task-info-card">
        <div class="task-header">
          <h2>{{ task.title }}</h2>
          <el-tag :type="getStatusType(task.status)">{{ task.status }}</el-tag>
        </div>
        <p class="task-description">{{ task.description }}</p>
        
        <div class="execution-actions">
          <el-button type="primary" @click="startTask" :disabled="task.status === '已完成' || task.status === '进行中'">
            开始任务
          </el-button>
          <el-button type="success" @click="completeTask" :disabled="task.status !== '进行中'">
            完成任务
          </el-button>
          <el-button type="warning" @click="pauseTask" :disabled="task.status !== '进行中'">
            暂停任务
          </el-button>
          <el-button type="danger" @click="reportIssue">
            报告问题
          </el-button>
        </div>

        <div class="execution-info">
          <div class="info-item">
            <span class="label">开始日期：</span>
            <span class="value">{{ formatDate(task.startDate) || '-' }}</span>
          </div>
          <div class="info-item">
            <span class="label">截止日期：</span>
            <span class="value">{{ formatDate(task.dueDate) }}</span>
          </div>
          <div class="info-item">
            <span class="label">负责人：</span>
            <span class="value">{{ task.assignee }}</span>
          </div>
          <div class="info-item">
            <span class="label">优先级：</span>
            <span class="value">
              <el-tag :type="getPriorityType(task.priority)">{{ task.priority }}</el-tag>
            </span>
          </div>
        </div>

        <div class="task-logs">
          <h3>任务日志</h3>
          <el-timeline>
            <el-timeline-item
              v-for="(log, index) in task.logs"
              :key="index"
              :timestamp="formatDateTime(log.timestamp)"
              :type="getLogType(log.type)"
            >
              <h4>{{ log.title }}</h4>
              <p>{{ log.description }}</p>
              <p v-if="log.user"><strong>操作人：</strong> {{ log.user }}</p>
            </el-timeline-item>
          </el-timeline>
        </div>

        <div class="add-log-section">
          <h3>添加日志</h3>
          <el-form :model="newLog" label-position="top">
            <el-form-item label="日志标题">
              <el-input v-model="newLog.title" placeholder="请输入日志标题" />
            </el-form-item>
            <el-form-item label="日志内容">
              <el-input
                v-model="newLog.description"
                type="textarea"
                :rows="4"
                placeholder="请描述任务进展或遇到的问题"
              />
            </el-form-item>
            <el-form-item label="日志类型">
              <el-select v-model="newLog.type" placeholder="请选择日志类型">
                <el-option label="进度更新" value="progress" />
                <el-option label="问题报告" value="issue" />
                <el-option label="决策记录" value="decision" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="addTaskLog">添加日志</el-button>
            </el-form-item>
          </el-form>
        </div>

        <div class="task-resources" v-if="task.resources && task.resources.length > 0">
          <h3>任务资源</h3>
          <el-table :data="task.resources" style="width: 100%">
            <el-table-column prop="name" label="资源名称" />
            <el-table-column prop="type" label="类型" />
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="primary" size="small" @click="viewResource(scope.row)">查看</el-button>
                <el-button type="success" size="small" @click="downloadResource(scope.row)">下载</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>

    <!-- 报告问题对话框 -->
    <el-dialog
      v-model="issueDialogVisible"
      title="报告问题"
      width="50%"
    >
      <el-form :model="issueForm" label-position="top">
        <el-form-item label="问题标题" required>
          <el-input v-model="issueForm.title" placeholder="请输入问题标题" />
        </el-form-item>
        <el-form-item label="问题描述" required>
          <el-input
            v-model="issueForm.description"
            type="textarea"
            :rows="6"
            placeholder="请详细描述您遇到的问题"
          />
        </el-form-item>
        <el-form-item label="问题严重程度">
          <el-select v-model="issueForm.severity" placeholder="请选择问题严重程度">
            <el-option label="低" value="low" />
            <el-option label="中" value="medium" />
            <el-option label="高" value="high" />
            <el-option label="阻塞" value="blocking" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="issueDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitIssue">提交问题</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'

export default {
  name: 'TaskExecution',
  setup() {
    const route = useRoute()
    const taskId = route.params.id
    const task = ref({})
    const loading = ref(true)
    const error = ref(null)
    const issueDialogVisible = ref(false)
    
    const newLog = reactive({
      title: '',
      description: '',
      type: 'progress'
    })
    
    const issueForm = reactive({
      title: '',
      description: '',
      severity: 'medium'
    })

    const fetchTaskData = async () => {
      try {
        loading.value = true
        // 这里替换为实际的 API 调用
        // const response = await fetch(`/api/tasks/${taskId}/execution`)
        // task.value = await response.json()
        
        // 模拟数据
        setTimeout(() => {
          task.value = {
            id: taskId,
            title: '前端组件开发',
            description: '开发任务进度跟踪组件，包括进度条、里程碑显示和状态更新功能',
            status: '进行中',
            startDate: '2024-05-10',
            dueDate: '2024-05-25',
            assignee: '张三',
            priority: '高',
            logs: [
              {
                title: '任务开始',
                description: '开始进行前端组件开发任务',
                timestamp: '2024-05-10T09:00:00',
                type: 'info',
                user: '张三'
              },
              {
                title: '完成设计稿评审',
                description: '与设计团队完成了设计稿评审，确认了最终的UI设计方案',
                timestamp: '2024-05-12T14:30:00',
                type: 'progress',
                user: '张三'
              },
              {
                title: '遇到技术问题',
                description: '在实现进度条动画时遇到性能问题，正在寻找解决方案',
                timestamp: '2024-05-15T11:20:00',
                type: 'issue',
                user: '张三'
              },
              {
                title: '问题已解决',
                description: '通过优化渲染逻辑解决了性能问题',
                timestamp: '2024-05-16T16:45:00',
                type: 'progress',
                user: '张三'
              }
            ],
            resources: [
              { name: '设计文档', type: 'PDF', url: '#' },
              { name: '组件原型', type: 'Figma', url: '#' },
              { name: '技术规范', type: 'Markdown', url: '#' }
            ]
          }
          loading.value = false
        }, 1000)
      } catch (err) {
        error.value = '获取任务数据失败'
        loading.value = false
        console.error(err)
      }
    }

    const formatDate = (dateString) => {
      if (!dateString) return null
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN')
    }

    const formatDateTime = (dateTimeString) => {
      if (!dateTimeString) return null
      const date = new Date(dateTimeString)
      return date.toLocaleString('zh-CN')
    }

    const getStatusType = (status) => {
      switch (status) {
        case '已完成':
          return 'success'
        case '进行中':
          return 'primary'
        case '未开始':
          return 'info'
        case '延期':
          return 'warning'
        case '阻塞':
          return 'danger'
        default:
          return 'info'
      }
    }

    const getPriorityType = (priority) => {
      switch (priority) {
        case '高':
          return 'danger'
        case '中':
          return 'warning'
        case '低':
          return 'info'
        default:
          return 'info'
      }
    }

    const getLogType = (type) => {
      switch (type) {
        case 'progress':
          return 'success'
        case 'issue':
          return 'danger'
        case 'decision':
          return 'warning'
        case 'info':
          return 'info'
        default:
          return 'info'
      }
    }

    const startTask = () => {
      // 实际应用中应调用 API 来更新任务状态
      task.value.status = '进行中'
      task.value.startDate = new Date().toISOString().split('T')[0]
      task.value.logs.unshift({
        title: '任务开始',
        description: '开始执行任务',
        timestamp: new Date().toISOString(),
        type: 'info',
        user: '当前用户'
      })
      ElMessage.success('任务已开始')
    }

    const completeTask = () => {
      // 实际应用中应调用 API 来更新任务状态
      task.value.status = '已完成'
      task.value.logs.unshift({
        title: '任务完成',
        description: '任务已成功完成',
        timestamp: new Date().toISOString(),
        type: 'progress',
        user: '当前用户'
      })
      ElMessage.success('任务已完成')
    }

    const pauseTask = () => {
      // 实际应用中应调用 API 来更新任务状态
      task.value.status = '暂停'
      task.value.logs.unshift({
        title: '任务暂停',
        description: '任务暂时暂停',
        timestamp: new Date().toISOString(),
        type: 'warning',
        user: '当前用户'
      })
      ElMessage.warning('任务已暂停')
    }

    const reportIssue = () => {
      issueDialogVisible.value = true
    }

    const submitIssue = () => {
      // 实际应用中应调用 API 来提交问题
      task.value.logs.unshift({
        title: issueForm.title,
        description: issueForm.description,
        timestamp: new Date().toISOString(),
        type: 'issue',
        user: '当前用户'
      })

      ElMessage.success('问题已报告')
      issueDialogVisible.value = false
      
      // 清空表单
      issueForm.title = ''
      issueForm.description = ''
      issueForm.severity = 'medium'
    }

    const addTaskLog = () => {
      if (!newLog.title || !newLog.description) {
        ElMessage.warning('请填写日志标题和内容')
        return
      }

      // 实际应用中应调用 API 来添加日志
      task.value.logs.unshift({
        title: newLog.title,
        description: newLog.description,
        timestamp: new Date().toISOString(),
        type: newLog.type,
        user: '当前用户'
      })

      ElMessage.success('日志已添加')
      
      // 清空表单
      newLog.title = ''
      newLog.description = ''
      newLog.type = 'progress'
    }

    const viewResource = (resource) => {
      // 在实际应用中应该打开资源链接或预览
      console.log('查看资源:', resource)
      ElMessage.info(`查看资源: ${resource.name}`)
    }

    const downloadResource = (resource) => {
      // 在实际应用中应该下载文件
      console.log('下载资源:', resource)
      ElMessage.success(`开始下载: ${resource.name}`)
    }

    onMounted(() => {
      fetchTaskData()
    })

    return {
      task,
      loading,
      error,
      newLog,
      issueForm,
      issueDialogVisible,
      formatDate,
      formatDateTime,
      getStatusType,
      getPriorityType,
      getLogType,
      startTask,
      completeTask,
      pauseTask,
      reportIssue,
      submitIssue,
      addTaskLog,
      viewResource,
      downloadResource
    }
  }
}
</script>

<style scoped>
.task-execution-container {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
}

.task-info-card {
  margin-bottom: 20px;
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.task-description {
  margin-bottom: 20px;
  color: #606266;
}

.execution-actions {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.execution-info {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  margin-bottom: 30px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.info-item {
  display: flex;
  flex-direction: column;
}

.label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.value {
  font-size: 16px;
  font-weight: 500;
}

.task-logs,
.add-log-section,
.task-resources {
  margin-top: 30px;
}

h3 {
  margin-bottom: 15px;
  font-size: 18px;
  font-weight: 500;
}

.loading-container,
.error-container {
  margin: 30px 0;
}
</style> 